package com.springboot.demo.seria_deseria.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.springboot.demo.seria_deseria.core.CountryEnum;
import com.springboot.demo.seria_deseria.util.CountryUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @desc mvc 全局配置
 * @author wanggang
 * @time 2024/11/25 11:50
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HeaderInterceptor())
                .addPathPatterns("/user/**")
                .excludePathPatterns("/test/**");
    }

//    @Override
//    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//        argumentResolvers.add(new LoginUserHandlerMethodArgumentResolver());
//    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for(int i = 0; i < converters.size(); i++){
            HttpMessageConverter<?> converter = converters.get(i);
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jsonMessageConverter = (MappingJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = jsonMessageConverter.getObjectMapper();
                //空值不序列化
                objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
                //Date文本格式化
                objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                //自定义时间序列器
                SimpleModule simpleModule = new SimpleModule();
                simpleModule.addSerializer(LocalDateTime.class, new CustomLocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                //定义反序列化
                simpleModule.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                simpleModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                simpleModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                objectMapper.registerModule(simpleModule);
                //类型不匹配时不进行解析，避免JsonMappingException异常
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                //禁用时间戳序列
                objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            }
        }
    }

    /**
     * LocalDateTime反序列化
     *
     */
    public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
    {
        private DateTimeFormatter formatter;

        public CustomLocalDateTimeDeserializer(DateTimeFormatter formatter)
        {
            super();
            this.formatter = formatter;
        }

        @Override
        public LocalDateTime deserialize(JsonParser parser, DeserializationContext context)
                throws IOException
        {
            //从threadLocal拿countryId
            Integer countryId = CountryUtil.getCountryId();
            if(null == countryId){
                //countryId 赋值为墨西哥
                countryId= CountryEnum.Mexico.getCountryId();
            }
            CountryEnum countryEnum=CountryEnum.getItem(countryId);
            ZoneId originZoneId=countryEnum.getZoneId();
            ZoneId mxZoneId = CountryEnum.Mexico.getZoneId();

            return convertLocalDateTime(LocalDateTime.parse(parser.getText(), formatter), originZoneId, mxZoneId);
        }

    }

    /**
     * LocalDateTime序列化
     */
    public static class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime>
    {
        private DateTimeFormatter formatter;

        public CustomLocalDateTimeSerializer(DateTimeFormatter formatter)
        {
            super();
            this.formatter = formatter;
        }

        @Override
        public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider)
                throws IOException
        {
            //从threadLocal拿countryId
            Integer countryId = CountryUtil.getCountryId();
            if(null == countryId){
                //countryId 赋值为墨西哥
                countryId=CountryEnum.Mexico.getCountryId();
            }
            CountryEnum countryEnum=CountryEnum.getItem(countryId);

            ZoneId mxZoneId = CountryEnum.Mexico.getZoneId();
            ZoneId targetZoneId=countryEnum.getZoneId();
            generator.writeString(convertLocalDateTime(value, mxZoneId, targetZoneId).format(formatter));
        }

    }

    /**
     * 时区转换
     *
     * @param localDateTime
     * @param originZoneId
     * @param targetZoneId
     * @return
     */
    public static LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId,
                                                     ZoneId targetZoneId)
    {
        return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime();
    }

}
